using GEM.Application.Common;
using GEM.Application.Dto.File;
using GEM.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace GEM.Api.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase
{
    private readonly FileService _fileService;
    public FileController(FileService fileService)
    {
        _fileService = fileService;
    }

    [HttpPost("upload")]
    public async Task<IActionResult> Upload()
    {
        try
        {
            // 手动从Request中获取文件和数据
            var form = await Request.ReadFormAsync();
            var file = form.Files.FirstOrDefault();
            var ownerId = form["ownerId"].FirstOrDefault();

            // 检查文件
            if (file == null)
                return BadRequest("No file uploaded");

            if (file.Length == 0)
                return BadRequest("File is empty");

            // 检查ownerId
            if (string.IsNullOrEmpty(ownerId))
                return BadRequest("OwnerId is required");

            if (!Guid.TryParse(ownerId, out var ownerGuid))
                return BadRequest($"Invalid ownerId format: {ownerId}");

            // 简单的测试：先尝试保存文件
            var fileId = Guid.NewGuid();
            var fileName = $"{fileId}_{file.FileName}";
            var filePath = Path.Combine("Uploads", fileName);

            // 确保目录存在
            Directory.CreateDirectory("Uploads");

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            // 创建简单的响应
            var result = new FileDto
            {
                Id = fileId,
                FileName = file.FileName,
                FilePath = fileName,
                Size = file.Length,
                ContentType = file.ContentType ?? "application/octet-stream",
                OwnerId = ownerGuid
            };

            return Ok(ApiResponse<FileDto>.Success(result));
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex.Message}");
        }
    }

    [HttpGet("download/{id}")]
    [AllowAnonymous]
    public async Task<IActionResult> Download(Guid id)
    {
        try
        {
            // 查找Uploads目录中的文件
            var uploadsDir = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");
            if (!Directory.Exists(uploadsDir))
                return NotFound("Uploads directory not found");

            // 查找包含该ID的文件
            var files = Directory.GetFiles(uploadsDir, $"*{id}*");
            if (files.Length == 0)
                return NotFound($"File with id {id} not found");

            var filePath = files[0];
            var fileName = Path.GetFileName(filePath);

            if (!System.IO.File.Exists(filePath))
                return NotFound("File not found");

            var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);
            var contentType = GetContentType(fileName);

            return File(fileBytes, contentType, fileName);
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Download failed: {ex.Message}");
        }
    }

    private string GetContentType(string fileName)
    {
        var extension = Path.GetExtension(fileName).ToLowerInvariant();
        return extension switch
        {
            ".png" => "image/png",
            ".jpg" => "image/jpeg",
            ".jpeg" => "image/jpeg",
            ".gif" => "image/gif",
            ".bmp" => "image/bmp",
            ".webp" => "image/webp",
            _ => "application/octet-stream"
        };
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        await _fileService.DeleteAsync(id);
        return NoContent();
    }
}
